// ActionList.cpp: implementation of the CActionList class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "client.h"
#include "ActionList.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////


CActionList::CActionList()
{
	pFirst = pLast = NULL;
	Clear();
}

CActionList::~CActionList()
{
	Clear();
}


void CActionList::Clear()
{
	TotNum = 0;
	pLast = NULL;
	if(pFirst == NULL) return;

	CActionNode* pNext = pFirst;
	while(pNext)
	{
		CActionNode* pNow = pNext;
		pNext = pNow->pNextNode;
		delete pNow;
	}

	pFirst = NULL;
	return;
}

BOOL CActionList::IsActionProcessed()
{
	if(!pFirst) return FALSE;
	return pFirst->bProcessed;
}

BOOL CActionList::AddAction(CBaseAction& act)
{
	if(act.Size <= 0) return FALSE;
	CBaseAction* pNew = (CBaseAction*)new char[act.Size];
	memcpy(pNew, &act, act.Size);
	return EnqueAction(pNew);
}

BOOL CActionList::EnqueAction(CBaseAction* pAct)
{
	if(!pAct) return FALSE;

	CActionNode* pNew = new CActionNode();
	if(pNew==NULL) return FALSE;

	pNew->pAct = pAct;

	TotNum++;

	if(pFirst == NULL) {
		pFirst = pLast = pNew;
		return TRUE;
	}

	pLast->pNextNode = pNew;
	pNew->pPreNode = pLast;
	pLast = pNew;

	return TRUE;
}

BOOL CActionList::DequeAction()
{
	if(TotNum <= 0) return FALSE;

	if(!pFirst) return FALSE;
	CActionNode* pNode = pFirst;

	if(TotNum>0) TotNum--;

	CActionNode* pNext = pNode->pNextNode;
	
	pFirst = pNext;
	if(pNext) pNext->pPreNode = NULL;
	else pLast = NULL;

	//CBaseAction *pAct = pNode->pAct;
	//pNode->pAct = NULL;
	delete pNode;
	//return pAct;
	return TRUE;
}

CBaseAction* CActionList::PeekAction()
{
	if(TotNum <= 0) return NULL;

	if(!pFirst) return NULL;
	return pFirst->pAct;
}

BOOL CActionList::DelAction(CBaseAction* pAct)
{
	if(!pAct) return FALSE;
	if(TotNum <= 0) return FALSE;

	CActionNode* pNode = FindAction(pAct);
	if(!pNode) return FALSE;

	if(TotNum>0) TotNum--;

	CActionNode* pPre = pNode->pPreNode;
	CActionNode* pNext = pNode->pNextNode;
	
	if(pPre) pPre->pNextNode = pNext;
	else pFirst = pNext;

	if(pNext) pNext->pPreNode = pPre;
	else pLast = pPre;

	if(!pPre && !pNext) pFirst = NULL;

	delete pNode;

	return TRUE;
}

CActionNode* CActionList::FindAction(CBaseAction* pAct)
{
	CActionNode* pNext = pFirst;
	while(pNext) {
		if(pNext->pAct == pAct) return pNext;
		pNext = pNext->pNextNode;
	}
	return NULL;
}

